/*!--------------------------------------------------------------------------
 @file sifilter.c
 @date 12/27/2010

 See header file for description.
 
*/
/*
 
 Copyright (c) 2010, XInfo
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
 
    * Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
    * Neither the name of the XInfo nor the names of its contributors may be
    used to endorse or promote products derived from this software without
    specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------*/

#include "xutility.h"
#include "siconst.h"
#include "sicommon.h"
#include "simat.h"
#include "sifilter.h"
#include <assert.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>

/*! Filter definition */
struct _SIFilter
{
    // gupeng
};


/*! Get kernel type.

 @return X Error
*/
static int
si_get_kernel_type(SIMat* kernel,                       /*!< Kernel matrix */
                   SIPoint* anchor,                     /*!< Kernel anchor */
                   int* kernel_type                     /*!< Kernel type (SI_KERNEL_GENERAL ~ SI_KERNEL_INTEGER) */
                   );

/*! Create Gaussian kernel.

 Calculate and return a new matrix of Gaussian kernel. Returned instance
 should be freed when useless.

 @return X Error
*/
static int
si_gaussian_kernel_create(int n,                        /*!< Size */
                          int depth,                    /*!< Depth */
                          double sigma,                 /*!< Sigma */
                          SIMat** mat                   /*!< Matrix created */
                          );


#pragma mark PublicMethods

/* See "sifilter.h" for description. */
int
si_separable_linear_filter_create(int src_type, int dst_type, SIMat* row_kernel, SIMat* column_kernel, int row_border_type, int column_border_type, SIPoint* anchor, double delta, SIFilter** filter)
{
    src_type = SI_GET_MATRIX_TYPE(src_type);
    dst_type = SI_GET_MATRIX_TYPE(dst_type);
    
}

Ptr<FilterEngine> createSeparableLinearFilter(
                                              int _srcType, int _dstType,
                                              const Mat& _rowKernel, const Mat& _columnKernel,
                                              Point _anchor, double _delta,
                                              int _rowBorderType, int _columnBorderType,
                                              const Scalar& _borderValue )
{
    // gupeng
    _srcType = CV_MAT_TYPE(_srcType);
    _dstType = CV_MAT_TYPE(_dstType);
    int sdepth = CV_MAT_DEPTH(_srcType), ddepth = CV_MAT_DEPTH(_dstType);
    int cn = CV_MAT_CN(_srcType);
    CV_Assert( cn == CV_MAT_CN(_dstType) );
    int rsize = _rowKernel.rows + _rowKernel.cols - 1;
    int csize = _columnKernel.rows + _columnKernel.cols - 1;
    if( _anchor.x < 0 )
        _anchor.x = rsize/2;
    if( _anchor.y < 0 )
        _anchor.y = csize/2;
//    int rtype = getKernelType(_rowKernel,
//                              _rowKernel.rows == 1 ? Point(_anchor.x, 0) : Point(0, _anchor.x));
//    int ctype = getKernelType(_columnKernel,
//                              _columnKernel.rows == 1 ? Point(_anchor.y, 0) : Point(0, _anchor.y));
//    Mat rowKernel, columnKernel;
    
    int bdepth = std::max(CV_32F,std::max(sdepth, ddepth));
    int bits = 0;
    
 //   if( sdepth == CV_8U &&
//       ((rtype == KERNEL_SMOOTH+KERNEL_SYMMETRICAL &&
//         ctype == KERNEL_SMOOTH+KERNEL_SYMMETRICAL &&
//         ddepth == CV_8U) ||
//        ((rtype & (KERNEL_SYMMETRICAL+KERNEL_ASYMMETRICAL)) &&
//         (ctype & (KERNEL_SYMMETRICAL+KERNEL_ASYMMETRICAL)) &&
//         (rtype & ctype & KERNEL_INTEGER) &&
//         ddepth == CV_16S)) )
//    {
//        bdepth = CV_32S;
//        bits = ddepth == CV_8U ? 8 : 0;
//        _rowKernel.convertTo( rowKernel, CV_32S, 1 << bits );
//        _columnKernel.convertTo( columnKernel, CV_32S, 1 << bits );
//        bits *= 2;
//        _delta *= (1 << bits);
//    }
//    else
//    {
//        if( _rowKernel.type() != bdepth )
//            _rowKernel.convertTo( rowKernel, bdepth );
//        else
//            rowKernel = _rowKernel;
//        if( _columnKernel.type() != bdepth )
//            _columnKernel.convertTo( columnKernel, bdepth );
//        else
//            columnKernel = _columnKernel;
//    }
    
    int _bufType = CV_MAKETYPE(bdepth, cn);
    Ptr<BaseRowFilter> _rowFilter = getLinearRowFilter(
                                                       _srcType, _bufType, rowKernel, _anchor.x, rtype);
    Ptr<BaseColumnFilter> _columnFilter = getLinearColumnFilter(
                                                                _bufType, _dstType, columnKernel, _anchor.y, ctype, _delta, bits );
    
    return Ptr<FilterEngine>( new FilterEngine(Ptr<BaseFilter>(0), _rowFilter, _columnFilter,
                                               _srcType, _dstType, _bufType, _rowBorderType, _columnBorderType, _borderValue ));
}

/* See "sifilter.h" for description. */
int
si_gaussian_filter_create(int type, SISize size, double sigma1, double sigma2, int border_type, SIFilter** filter)
{
    if(NULL == filter)
    {
        RES_ERR(X_INVAL, "");
    }
    if(sigma2 <= 0)
    {
        sigma2 = sigma1;
    }

    // Calculate kernel width and height from sigma.
    if(size.width <= 0 && sigma1 > 0)
    {
        size.width = si_lrint(sigma1 * 3.0) * 2 + 1;
    }
    if(size.height <= 0 && sigma2 > 0)
    {
        size.height = si_lrint(sigma2 * 3.0) * 2 + 1;
    }

    if(size.width <= 0 || size.width % 2 != 1 || size.height <= 0 || size.height % 2 != 1)
    {
        RES_ERR(X_INVAL, "");
    }

    sigma1 = sigma1 >= 0.0 ? sigma1 : 0.0;
    sigma2 = sigma2 >= 0.0 ? sigma2 : 0.0;

    // Create Gaussian kernel.
    type = SI_GET_MATRIX_TYPE(type);
    int depth = SI_GET_DEPTH(type);
    SIMat* kx = NULL;
    int err = si_gaussian_kernel_create(size.width, depth <= SI_32F ? SI_32F : depth, sigma1, &kx);
    if(err != 0)
    {
        RES_ERR(err, "");
    }
    assert(kx != NULL);
    SIMat* ky = NULL;
    if(size.width == size.height && fabs(sigma1 - sigma2) < DBL_EPSILON)
    {
        err = simat_create_by_copy(kx, &ky);
        if(err != 0)
        {
            simat_destroy(kx);
            RES_ERR(err, "");
        }
    }
    else
    {
        err = si_gaussian_kernel_create(size.height, depth <= SI_32F ? SI_32F : depth, sigma2, &ky);
        if(err != 0)
        {
            simat_destroy(kx);
            RES_ERR(err, "");
        }
    }

    // Create filter.
//    err = si_separable_linear_filter_create(channels, depth, kx, ky, );
        // gupeng
    return 0;
//    return createSeparableLinearFilter( type, type, kx, ky, Point(-1,-1), 0, borderType );    
}

/* See "sifilter.h" for description. */
void
sifilter_destroy(SIFilter* filter)
{
    if(filter != NULL)
    {
        free(filter);
        filter = NULL;
    }
}

/* See "sifilter.h" for description. */
int
sifilter_apply(SIFilter* filter, SIMat* src, SIMat* dst)
{
    // gupeng
    return 0;
}


#pragma mark PrivateMethods

/* See declaration for description. */
int
si_get_kernel_type(SIMat* kernel, SIPoint* anchor, int* kernel_type)
{
    if(NULL == kernel || NULL == anchor || NULL == kernel_type)
    {
        RES_ERR(X_INVAL, "");
    }

    // Kernel channels should be always 1.
    int channels = 0;
    int err = simat_get_channels(kernel, &channels);
    if(err != 0)
    {
        RES_ERR(err, "");
    }
    if(channels != 1)
    {
        RES_ERR(X_INVAL, "");
    }

    // Get rows columns and size.
    int rows = 0;
    err = simat_get_rows(kernel, &rows);
    if(err != 0)
    {
        RES_ERR(err, "");
    }
    int columns = 0;
    err = simat_get_columns(kernel, &columns);
    if(err != 0)
    {
        RES_ERR(err, "");
    }
    int size = 0;
    err = simat_get_size(kernel, &size);
    if(err != 0)
    {
        RES_ERR(err, "");
    }

    // gupeng
}

int getKernelType(const Mat& _kernel, Point anchor)
{
    CV_Assert( _kernel.channels() == 1 );
    int i, sz = _kernel.rows*_kernel.cols;
    
    Mat kernel;
    _kernel.convertTo(kernel, CV_64F);

    // gupeng
    const double* coeffs = (double*)kernel.data;
    double sum = 0;
    int type = KERNEL_SMOOTH + KERNEL_INTEGER;
    if( (_kernel.rows == 1 || _kernel.cols == 1) &&
       anchor.x*2 + 1 == _kernel.cols &&
       anchor.y*2 + 1 == _kernel.rows )
        type |= (KERNEL_SYMMETRICAL + KERNEL_ASYMMETRICAL);
    
    for( i = 0; i < sz; i++ )
    {
        double a = coeffs[i], b = coeffs[sz - i - 1];
        if( a != b )
            type &= ~KERNEL_SYMMETRICAL;
        if( a != -b )
            type &= ~KERNEL_ASYMMETRICAL;
        if( a < 0 )
            type &= ~KERNEL_SMOOTH;
        if( a != saturate_cast<int>(a) )
            type &= ~KERNEL_INTEGER;
        sum += a;
    }
    
    if( fabs(sum - 1) > FLT_EPSILON*(fabs(sum) + 1) )
        type &= ~KERNEL_SMOOTH;
    return type;
}


/* See declaration for description. */
int
si_gaussian_kernel_create(int n, int depth, double sigma, SIMat** mat)
{
    if((n <= 0 || n % 2 != 1) || depth < SI_32F || NULL == mat)
    {
        RES_ERR(X_INVAL, "");
    }

    const float* fixed_kernel = n <= SMALL_GAUSSIAN_SIZE && sigma <= 0 ? small_gaussian_table[n >> 1] : NULL;

    int type = SI_MAKE_TYPE(depth, 1);
    SIMat* kernel = NULL;
    int err = simat_create(n, 1, type, &kernel);
    if(err != 0)
    {
        RES_ERR(err, "");
    }

    double scale = 0.0;
    if(NULL == fixed_kernel)
    {
        sigma = sigma > 0.0 ? sigma : ((n - 1) * 0.5 - 1) * 0.3 + 0.8;
        scale = -0.5 / (sigma * sigma);
    }
    double sum = 0.0;

    void* data = NULL;
    err = simat_get_data(kernel, &data);
    if(err != 0)
    {
        simat_destroy(kernel);
        RES_ERR(err, "");
    }
    float* cell_float = (float*)data;
    double* cell_double = (double*)data;

    int i = 0;
    for(i = 0; i < n; ++i)
    {
        double x = (1 - n) * 0.5 + i;
        double t = fixed_kernel != NULL ? (double)fixed_kernel[i] : exp(scale * x * x);
        if(SI_32F == depth)
        {
            cell_float[i] = (float)t;
            sum += cell_float[i];
        }
        else
        {
            assert(SI_64F == depth);
            cell_double[i] = t;
            sum += cell_double[i];
        }
    }

    sum = 1.0 / sum;
    for(i = 0; i < n; ++i)
    {
        if(SI_32F == depth)
        {
            cell_float[i] = (float)(cell_float[i] * sum);
        }
        else
        {
            assert(SI_64F == depth);
            cell_double[i] *= sum;
        }
    }

    *mat = kernel;
    return 0;
}
